﻿using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Diagnostics;

namespace MEMZEffectTest
{
    internal static class Program
    {
        // 导入Windows API以设置DPI感知
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool SetProcessDPIAware();

        [DllImport("shcore.dll", SetLastError = true)]
        private static extern int SetProcessDpiAwareness(int PROCESS_DPI_AWARENESS);

        private enum DpiAwareness
        {
            None = 0,
            SystemAware = 1,
            PerMonitorAware = 2
        }

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                // 设置DPI感知
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    // 防御性编程：检查API是否可用
                    try
                    {
                        if (Environment.OSVersion.Version.Build >= 14393)
                        {
                            // DpiAwareness.PerMonitorAware 常数不能直接使用，需要将其转换为 int 类型后再传入
                            // SetProcessDpiAwareness 方法。
                            if (SetProcessDpiAwareness((int)DpiAwareness.PerMonitorAware) != 0)
                            {
                                throw new Win32Exception(Marshal.GetLastWin32Error());
                            }
                        }
                        else
                        {
                            if (!SetProcessDPIAware())
                            {
                                throw new Win32Exception(Marshal.GetLastWin32Error());
                            }
                        }
                    }
                    catch (DllNotFoundException dllEx)
                    {
                        Debug.WriteLine($"DPI设置失败：缺少DLL文件 - {dllEx.Message}");
                    }
                    catch (EntryPointNotFoundException entryEx)
                    {
                        Debug.WriteLine($"DPI设置失败：找不到API入口点 - {entryEx.Message}");
                    }
                    catch (Win32Exception winEx)
                    {
                        Debug.WriteLine($"DPI设置失败：错误代码 0x{winEx.ErrorCode:X8}");
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"DPI设置失败：未知错误 - {ex.Message}");
                    }
                }

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            catch (Exception ex)
            {
                // 防御性编程：捕获所有未处理异常
                MessageBox.Show($"应用程序启动时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
